package com.feeyo.prophet.actions.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feeyo.llm.agent.engine.Action;
import com.feeyo.llm.agent.engine.ActionCategory;

import com.feeyo.llm.agent.engine.ActionResult;
import com.feeyo.llm.agent.engine.ExecuteOptions;
import lombok.extern.slf4j.Slf4j;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.springframework.http.HttpStatus;

/**
 * 计算类
 * @author lihu
 */
@Slf4j
public class CalculateAction implements Action {
	
	@Override
	public String human() {
		return "计算器";
	}
	//
	@Override
	public String name() {
		return "calculate";
	}

	@Override
	public String eg() {
		return null;
	}

	@Override
	public String description() {
		return "Runs a calculation and returns the number - expressions need to be compatible with Rhino JavaScript Engine";
	}

	@Override
	public ActionCategory[] category() {
		return new ActionCategory[]{ActionCategory.COMMON, ActionCategory.DICTIONARY};
	}

	@Override
	public String parameters() {
		return """
		{
			"type": "object",
			"properties": {
				"data": {
					"type": "string",
					"description": "mathematical formulas",
				}
			}
		}
		""";
	}

	@Override
	public ActionResult run(String question, String input, ExecuteOptions options) throws Exception {
		Context rhino = Context.enter();
		try {
			JSONObject jsonObject = JSON.parseObject(input);
			String dataObject = (String)jsonObject.get("data");
			Scriptable scope = rhino.initStandardObjects();
			Object result = rhino.evaluateString(scope, dataObject, "JavaScript", 1, null);
			return new ActionResult(HttpStatus.OK.value(), Context.toString(result));
		} catch (Exception e) {
			log.error("Calculation error", e);
			return new ActionResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Calculation error: " + e.getMessage());
		} finally {
			Context.exit();
		}
	}
}
